package com.itbooking.service.pay;

import com.itbooking.core.threalLocal.UserThreadLocal;
import com.itbooking.mapper.OrderMapper;
import com.itbooking.mapper.ProductMapper;
import com.itbooking.pojo.OrderDo;
import com.itbooking.pojo.ProductDo;
import com.itbooking.pojo.UserDo;
import com.itbooking.vo.OrderVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 订单处理的Service层
 */
@Service
@Log4j2
public class PayServiceImpl implements  IPayService{


    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductMapper productMapper;

    public OrderDo mainPayOperator(OrderVo orderVo){
        OrderDo orderDo = null;
        if(orderVo!=null && orderVo.getOrderid()!=null){
            orderDo = orderMapper.selectById(orderVo.getOrderid());
            // 这里要同步状态
            orderDo.setStatus(orderVo.getStatus());
            orderMapper.updateById(orderDo);
        }else{ orderDo = new OrderDo();
            // 从本地线程副本中获取登录的用户信息。
            UserDo userDo = UserThreadLocal.get();
            log.info("支付成功保存订单开始，相关参数是：{}",orderVo);
            //1:支付的用户
            if(userDo!=null) {
                orderDo.setUserid(userDo.getId());
                orderDo.setAvartarurl(userDo.getAvatarUrl());
                orderDo.setTelephone(userDo.getTelephone());
                orderDo.setOpenid(userDo.getOpenid());
            }


            //2:相关的产品信息
            ProductDo productDo = productMapper.selectById(orderVo.getProductid());
            if(productDo!=null) {
                orderDo.setPrice(productDo.getTprice().doubleValue());
                orderDo.setProdtitle(productDo.getTitle());
                orderDo.setProddesc(productDo.getDescription());
                orderDo.setProdimg(productDo.getImg());
            }
            //3：其他相关信息
            orderDo.setIp("127.10.1.2");
            orderDo.setIpaddress("广州");
            // 4:status状态
            orderDo.setStatus(orderVo.getStatus());
            //5:订单编号
            orderDo.setOrdernumber(orderVo.getOrdernumber());
            orderMapper.insert(orderDo);
        }

        return orderDo;
    }
}
